<template>
  <a-modal
    v-model="modalVisible"
    title="项目群设置"
    width="1000px"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <a-form layout="inline">
      <a-form-item label="项目名称" style="width: 60%;">
        <a-input autocomplete="off" disabled :default-value="formData.name" />
      </a-form-item>
      <a-form-item label="类型" style="width: 30%;">
        <a-select disabled :default-value="formData.belongType" style="width: 100%;">
          <span slot="suffixIcon"></span>
          <a-select-option v-for="item in projectBelongs" :key="item.key" :value="item.key" :title="item.title">{{item.title}}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="是否有指挥部" style="width: 100%;">
        <a-switch checked-children="是" un-checked-children="否" v-model="formData.isDirectorate" />
      </a-form-item>
      <a-form-item label="添加关联项目" style="width: 100%;">
        <a-button type="primary" size="small" :disabled="loading" @click="onAdd">添加行</a-button>
        <a-table
          class="requiredFormItem"
          bordered
          rowKey="index"
          :loading="loading"
          :scroll="{ y: 500 }"
          :columns="[
            { title: '序号', width: 100, customRender: (text, record, index) => `${index + 1}` },
            { title: '关联项目名称', dataIndex: 'projectName', scopedSlots: { customRender: 'projectName' } },
            { title: '操作', width: 100, scopedSlots: { customRender: 'operation' } },
          ]"
          :data-source="relationProject"
          :pagination="false"
          style="width: 100%;"
        >
          <template slot="projectName" slot-scope="text, record, index">
            <a-select
              show-search
              :default-value="record.projectId"
              option-filter-prop="children"
              style="width: 100%;"
              placeholder="请选择"
              @change="onProjectSelected($event, index)"
            >
              <a-select-option
                v-for="item in relationList"
                :key="item.projectId"
                :value="item.projectId"
                :title="item.projectName"
                :disabled="formData.relationProjectIds.some(id => id === item.projectId)"
              >{{item.projectName}}</a-select-option>
            </a-select>
          </template>
          <template slot="operation" slot-scope="text, record, index">
            <a-popconfirm title="确定要删除?" @confirm="onDelete(record, index)">
              <a-button type="link" size="small">删除</a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </a-form-item>
    </a-form>
    <template slot="footer">
      <a-button type="primary" :disabled="loading" :loading="confirmLoading" @click="handleOk">提交</a-button>
      <a-button type="default" @click="handleCancel">关闭</a-button>
    </template>
  </a-modal>
</template>

<script>
import { projectBelongs } from './eum.js'
import { getProjectGroupDetail, getRelationProjectList, setProjectGroup } from '@/api/system/system'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    defaultData: {
      type: Object,
      default: {}
    },
  },
  data(){
    return {
      projectBelongs,
      formData: {
        name: '',
        projectId: '',
      },
      confirmLoading: false,
      loading: false,
      relationList: [],
    }
  },
  computed: {
    modalVisible: {
      get: function(){
        if(this.visible){
          this.init()
        }
        return this.visible
      },
      set: function(val){
        this.$emit('update:visible', val)
      }
    },
    relationProject(){
      return (this.formData.relationProjectIds || []).map((id, index) => {
        const relationItem = {
          ...this.relationList.find(item => item.projectId === id),
          index
        }
        return !!relationItem ? relationItem : { projectId: id, projectName: '', index }
      })
    },
  },
  methods: {
    init(){
      const { name, id, branchComId } = this.defaultData
      this.formData = {
        projectId: id,
        name,
        belongType: 3,
        branchComId,
        isDirectorate: true,
        relationProjectIds: []
      }
      this.relationList = []
      this.getRelationProjectList()
      this.getProjectGroupDetail()
    },
    getRelationProjectList(){
      getRelationProjectList({}).then(res => {
        if(res.code == 200){
          res.data.forEach(item => {
            if(!this.relationList.some(i => i.projectId === item.projectId)){
              this.relationList.push(item)
            }
          })
        }
        this.relationList = this.relationList.filter(item => item.projectId !== this.defaultData.id)
      })
    },
    getProjectGroupDetail(){
      this.loading = true
      getProjectGroupDetail({
        projectId: this.formData.projectId
      }).then(res => {
        if(res.code == 200){
          this.formData.isDirectorate = res.data.isDirectorate ?? this.formData.isDirectorate
          this.formData.relationProjectIds = res.data.relationList.map(item => item.projectId).filter(id => this.formData.projectId !== id)
          res.data.relationList.forEach(item => {
            if(!this.relationList.some(i => i.projectId === item.projectId)){
              this.relationList.push(item)
            }
          })
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    onAdd(){
      this.formData.relationProjectIds.push(undefined)
    },
    onProjectSelected(id, index){
      this.formData.relationProjectIds = this.formData.relationProjectIds.map((_id, i) => {
        return i == index ? id : _id
      })
    },
    onDelete(_, index){
      this.formData.relationProjectIds.splice(index, 1)
    },
    handleOk(){
      if(this.relationProject.some(item => !item.projectName)){
        this.$message.error('关联项目名称不能为空！')
        return
      }
      this.confirmLoading = true
      setProjectGroup({
        branchComId: this.formData.branchComId,
        isDirectorate: this.formData.isDirectorate,
        mainProjectId: this.formData.projectId,
        relationProjectIds: this.formData.relationProjectIds,
      }).then(res => {
        this.confirmLoading = false
        if(res.data.code == 200){
          this.$message.success('保存成功！')
        }
        this.modalVisible = false
        this.$emit('submit')
      }).catch(() => {
        this.confirmLoading = false
      })
    },
    handleCancel(){
      this.modalVisible = false
    },
  }
}
</script>